<template>
  <ArticleForm v-model="form" mode="add" @save="handleSave" />
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useRequest } from '@/composables/useRequest';
import { useArticleAutoSave } from './hooks/useArticleAutoSave';
import ArticleForm from '@/views/myPiece/components/ArticleForm.vue';
import { addMyPiece, updateMyPiece } from '@/api/piece';
import type { addUpdateMyPieceRequest } from '@/types/piece';
import { ElMessage } from 'element-plus';
import { ArticleContentType } from '@/constant/article';
import { useRouter } from 'vue-router';

const router = useRouter();

const form = reactive<addUpdateMyPieceRequest>({
  title: '',
  tags: [],
  cover_image: '',
  category: '',
  desc: '',
  visible: '',
  content: '',
  content_type: ArticleContentType.HTML,
  status: 'draft',
  articleContent: '',
  editorValue: ''
});

const { run } = useRequest();

// 自动保存，每30秒调用一次 handleSave
useArticleAutoSave(form, (data) => handleSave(data, true), 30000);

async function handleSave(val: addUpdateMyPieceRequest, isAuto = false) {
  await run(
    () => (articleId.value ? updateMyPiece(articleId.value, val) : addMyPiece(val)),
    {
      onSuccess: (res) => {
        if (!articleId.value && res.data?.id) {
          articleId.value = res.data.id;
        }
        if (isAuto) {
          ElMessage.success('自动保存成功');
        } else {
          ElMessage.success('文章新建成功');
          router.back();
        }
      },
      onError: (err) => {
        if (isAuto) {
          console.warn('自动保存失败:', err);
        } else {
          ElMessage.error(err.message || '文章新建失败');
        }
      }
    }
  );
}
const articleId = ref<string | null>(null);
</script>

<style scoped></style>
